package com.hanxiaozhang.basicknowledgecode.compiler;

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.io.*;

import javax.tools.*;
import java.net.URI;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 〈一句话功能简述〉<br>
 * 〈〉
 *
 * @author hanxinghua
 * @create 2023/12/22
 * @since 1.0.0
 */
public class CompilerNode {


    public static void main(String[] args) throws IOException {
        // Java源代码
        String sourceCode = "public class HelloWorld {\n" +
                "    public static void main(String[] args) {\n" +
                "        System.out.println(\"Hello, world!1\");\n" +
                "    }\n" +
                "}";

//        String s = codeToClass(sourceCode, "HelloWorld.java", "D://");
//
//        System.out.println(s);



    }


    /**
     * java字符串代码，转为class文件
     **/
    public static String codeToClass(String code, String className, String compilePath) {
        JavaCompiler javaCompiler = ToolProvider.getSystemJavaCompiler();
        StandardJavaFileManager fileManager = javaCompiler.getStandardFileManager(null, null, null);
        JavaFileObject stringObject = new StringObject(className, code);
        // compilePath 指定编译的class文件的路径
        List<String> options = Arrays.asList("-d", compilePath);
        JavaCompiler.CompilationTask task = javaCompiler.getTask(null, fileManager, null, options, null, Collections.singletonList(stringObject));
        if (task.call()) {
            String classFileName = className.replace("java", "class");
            return compilePath + classFileName;
        } else {
            return null;
        }
    }


    public static class StringObject extends SimpleJavaFileObject {
        private final String content;

        public StringObject(String className, String contents) {
            super(URI.create(className), Kind.SOURCE);
            this.content = contents;
        }

        @Override
        public CharSequence getCharContent(boolean ignoreEncodingErrors) {
            return content;
        }
    }


}
